package com.xyzq.simpson.apm.web.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @date 2020/3/25 12:22
 */
public class TimeUtils {

    public static long time2Ti(String time) throws ParseException {
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format.parse(time);
        return date.getTime();
    }

    public static double differential(long start, long end) {
        return  (double)(end - start)/3600/1000;
    }

    public static String getOneDayAgo(String time) throws ParseException {
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format.parse(time);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        date = calendar.getTime();
        return format.format(date);
    }

    public static String getStringTimeFromCalendar(Calendar now) {
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(now.getTime());
    }

    public static String getStringTimeFromDate(Date data) {
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(data);
    }

    public static String getStringTimeFromTimestamp(long timestamp) {
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(timestamp);
    }

    public static String[] past7Days() {
        SimpleDateFormat sd = new SimpleDateFormat("MM-dd");
        String[] arr = new String[7];
        for(int i = 6; i >= 0; i--) {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DATE, - i);
            Date d = c.getTime();
            arr[6-i] = sd.format(d);
        }
        return arr;
    }

    public static List<Long> past7DaysAllHours(String date) throws ParseException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = sd.parse("2021-" + date + " 00:00:00");
        List<Long> list = new ArrayList<>(7*24);
        Calendar c = Calendar.getInstance();
        c.setTime(parse);
        for(int i = 0; i < 24*7; i++) {
            list.add(c.getTimeInMillis());
            c.add(Calendar.HOUR, 1);
        }
        return list;
    }

    public static long getStartTimestampByDate(String date) throws ParseException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = sd.parse("2021-" + date + " 00:00:00");
        return parse.getTime();
    }

    public static long getEndTimestampByDate(String date) throws ParseException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = sd.parse("2021-" + date + " 23:59:59");
        return parse.getTime();
    }
}
